package com.scx.controller.admin;

import com.scx.dto.BookDTO;
import com.scx.dto.BookPageQueryDTO;
import com.scx.entity.Book;
import com.scx.result.PageResult;
import com.scx.result.Result;
import com.scx.service.BookService;
import com.scx.vo.BookVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 图书管理
 */
@RestController
@RequestMapping("/admin/book")
@Api("图书相关接口")
@Slf4j
public class BookController {
    @Autowired
    BookService bookService;

    @PostMapping
    @ApiOperation("新增图书")
    @CacheEvict(cacheNames = "bookCache" , key = "#bookDTO.categoryId")
    public Result save(@RequestBody BookDTO bookDTO){
        log.info("新增图书：{}",bookDTO);
        bookService.saveWithGifts(bookDTO);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("图书分页查询")
    public Result<PageResult> page(BookPageQueryDTO bookPageQueryDTO){
        log.info("图书分页查询:{}",bookPageQueryDTO);
        PageResult pageResult = bookService.pageQuery(bookPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    @ApiOperation("图书批量删除")
    @CacheEvict(cacheNames = "bookCache" , allEntries = true)
    public Result delete(@RequestParam List<Long> ids){
        log.info("图书批量删除：{}", ids);
        bookService.deleteBatch(ids);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询图书")
    public Result<BookVO> getById(@PathVariable Long id){
        log.info("根据id查询图书:{}",id);
        BookVO bookVO = bookService.getByIdWithGifts(id);
        return Result.success(bookVO);
    }

    @PutMapping
    @ApiOperation("修改图书")
    @CacheEvict(cacheNames = "bookCache" , allEntries = true)
    public Result update(@RequestBody BookDTO bookDTO){
        log.info("修改图书:{}",bookDTO);
        bookService.updateWithGifts(bookDTO);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询图书")
    public Result<List<Book>> list(Long categoryId){
        log.info("根据分类id查询图书:{}",categoryId);
        List<Book> bookList = bookService.list(categoryId);
        return Result.success(bookList);
    }

    @PostMapping("/status/{status}")
    @ApiOperation("图书启售停售")
    @CacheEvict(cacheNames = "bookCache" , allEntries = true)
    public Result startOrStop(@PathVariable Integer status, Long id){
        log.info("图书启售停售:{},{}",status,id);
        bookService.startOrStop(status,id);
        return Result.success();
    }
}
